//
// Created by root on 20-3-7.
//

#include <iostream>

#include "srs_kernel_error.hpp"
#include "srs_kernel_log.hpp"
#include "srs_app_log.hpp"
#include "srs_service_log.hpp"
#include <srs_app_config.hpp>
#include <sstream>
#include <unistd.h>
#include "srs_app_listener.hpp"
#include "st.h"
using namespace std;

class  SipUdpListen:public  SrsUdpListener
{
public :
    SipUdpListen(ISrsUdpHandler* h, std::string i, int p):SrsUdpListener(h,i,p)
    {

    }
public:

    void SendData(const sockaddr* from)
    {
        st_sendto((st_netfd_t)stfd(),"123456",6,from,sizeof(struct sockaddr),ST_UTIME_NO_TIMEOUT);

    }
};

class UdpTest : virtual public ISrsUdpHandler
{
    virtual srs_error_t on_udp_packet(const sockaddr* from, const int fromlen, char* buf, int nb_buf)
    {
        srs_trace("on_udp_packet nb_buf=");

        sipUdpListen->SendData(from);
        return srs_success;
    }

public:
    SipUdpListen *sipUdpListen;
};


// @global log and context.
ISrsLog* _srs_log = new SrsFastLog();
ISrsThreadContext* _srs_context = new SrsThreadContext();
SrsConfig* _srs_config = new SrsConfig();



int main(int argc, char** argv) {
    std::cout << "Hello, World!" << std::endl;

    srs_error_t err = srs_success;

    // never use srs log(srs_trace, srs_error, etc) before config parse the option,
    // which will load the log config and apply it.
    if ((err = _srs_config->parse_options(argc, argv)) != srs_success) {
        srs_error_wrap(err, "config parse options");
    }
    // change the work dir and set cwd.
    int r0 = 0;
    string cwd = _srs_config->get_work_dir();
    if (!cwd.empty() && cwd != "./" && (r0 = chdir(cwd.c_str())) == -1) {
        srs_error_new(-1, "chdir to %s, r0=%d", cwd.c_str(), r0);
    }
    if ((err = _srs_config->initialize_cwd()) != srs_success) {
        srs_error_wrap(err, "config cwd");
    }

    // config parsed, initialize log.
    if ((err = _srs_log->initialize()) != srs_success) {
        srs_error_wrap(err, "log initialize");
    }

    if ((err = srs_st_init()) != srs_success) {
         srs_error_wrap(err, "initialize st failed");
    }

    string ip ="192.168.31.18";
    int port  = 5060;
    UdpTest *udpTest = new UdpTest();
    SipUdpListen *listener = new SipUdpListen(udpTest,ip,port);
    if ((err = listener->listen()) != srs_success) {
         srs_error_wrap(err, "listen %s:%d", ip.c_str(), port);
    }
    udpTest->sipUdpListen = listener;

    srs_info("333333");
    while (true)
    {
        srs_usleep(5000000);
        ;
    }
    return 0;
}